<?php
class ModelCatalogCategory extends Model {
	public function addCategory($data) {
		$this->db->query("INSERT INTO " . DB_PREFIX . "category SET parent_id = '" . (int) $data['parent_id'] . "', `top` = '" . (isset($data['top']) ? (int) $data['top'] : 0) . "', `column` = '" . (int) $data['column'] . "', sort_order = '" . (int) $data['sort_order'] . "', status = '" . (int) $data['status'] . "', date_modified = NOW(), date_added = NOW()");
		
		$category_id = $this->db->getLastId();
		
		if (isset($data['image'])) {
			$this->db->query("UPDATE " . DB_PREFIX . "category SET image = '" . $this->db->escape(html_entity_decode($data['image'], ENT_QUOTES, 'UTF-8')) . "' WHERE category_id = '" . (int) $category_id . "'");
		}
		
		foreach ($data['category_description'] as $language_id => $value) {
			$this->db->query("INSERT INTO " . DB_PREFIX . "category_description SET category_id = '" . (int) $category_id . "', language_id = '" . (int) $language_id . "', name = '" . $this->db->escape($value['name']) . "', meta_keyword = '" . $this->db->escape($value['meta_keyword']) . "', meta_description = '" . $this->db->escape($value['meta_description']) . "', description = '" . $this->db->escape($value['description']) . "'");
		}
		
		if (isset($data['category_store'])) {
			foreach ($data['category_store'] as $store_id) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "category_to_store SET category_id = '" . (int) $category_id . "', store_id = '" . (int) $store_id . "'");
			}
		}
		
		if (isset($data['category_layout'])) {
			foreach ($data['category_layout'] as $store_id => $layout) {
				if ($layout['layout_id']) {
					$this->db->query("INSERT INTO " . DB_PREFIX . "category_to_layout SET category_id = '" . (int) $category_id . "', store_id = '" . (int) $store_id . "', layout_id = '" . (int) $layout['layout_id'] . "'");
				}
			}
		}
		
		if ($data['keyword']) {
			$this->db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'category_id=" . (int) $category_id . "', keyword = '" . $this->db->escape($data['keyword']) . "'");
		}
		
		$this->cache->delete('category');
		return $category_id;
	}
	public function editCategory($category_id, $data) {
		$this->db->query("UPDATE " . DB_PREFIX . "category SET parent_id = '" . (int) $data['parent_id'] . "', `top` = '" . (isset($data['top']) ? (int) $data['top'] : 0) . "', `column` = '" . (int) $data['column'] . "', sort_order = '" . (int) $data['sort_order'] . "', status = '" . (int) $data['status'] . "', date_modified = NOW() WHERE category_id = '" . (int) $category_id . "'");
		
		if (isset($data['image'])) {
			$this->db->query("UPDATE " . DB_PREFIX . "category SET image = '" . $this->db->escape(html_entity_decode($data['image'], ENT_QUOTES, 'UTF-8')) . "' WHERE category_id = '" . (int) $category_id . "'");
		}
		
		$this->db->query("DELETE FROM " . DB_PREFIX . "category_description WHERE category_id = '" . (int) $category_id . "'");
		
		foreach ($data['category_description'] as $language_id => $value) {
			$this->db->query("INSERT INTO " . DB_PREFIX . "category_description SET category_id = '" . (int) $category_id . "', language_id = '" . (int) $language_id . "', name = '" . $this->db->escape($value['name']) . "', meta_keyword = '" . $this->db->escape($value['meta_keyword']) . "', meta_description = '" . $this->db->escape($value['meta_description']) . "', description = '" . $this->db->escape($value['description']) . "'");
		}
		
		$this->db->query("DELETE FROM " . DB_PREFIX . "category_to_store WHERE category_id = '" . (int) $category_id . "'");
		
		if (isset($data['category_store'])) {
			foreach ($data['category_store'] as $store_id) {
				$this->db->query("INSERT INTO " . DB_PREFIX . "category_to_store SET category_id = '" . (int) $category_id . "', store_id = '" . (int) $store_id . "'");
			}
		}
		
		$this->db->query("DELETE FROM " . DB_PREFIX . "category_to_layout WHERE category_id = '" . (int) $category_id . "'");
		
		if (isset($data['category_layout'])) {
			foreach ($data['category_layout'] as $store_id => $layout) {
				if ($layout['layout_id']) {
					$this->db->query("INSERT INTO " . DB_PREFIX . "category_to_layout SET category_id = '" . (int) $category_id . "', store_id = '" . (int) $store_id . "', layout_id = '" . (int) $layout['layout_id'] . "'");
				}
			}
		}
		
		$this->db->query("DELETE FROM " . DB_PREFIX . "url_alias WHERE query = 'category_id=" . (int) $category_id . "'");
		
		if ($data['keyword']) {
			$this->db->query("INSERT INTO " . DB_PREFIX . "url_alias SET query = 'category_id=" . (int) $category_id . "', keyword = '" . $this->db->escape($data['keyword']) . "'");
		}
		
		// 		$this->db->query ( "DELETE FROM " . DB_PREFIX . "attribute WHERE product_cat=" . (int)$category_id );
		// 		foreach ( $data ['attribute'] as $cat ) {
		// 			$this->db->query ( "INSERT INTO " . DB_PREFIX . "attribute(attribute_id,sort_order,product_cat,is_required,is_screen,is_default)
		// 					VALUES({$cat},".intval ($data['cat_order_'. $cat]).",{$category_id}," . intval ( $data ['is_required_' . $cat] ) . "," . intval ( $data ['is_screen_' . $cat] ) . "," . intval ( $data ['is_default_' . $cat] ) . ")" );
		// 		}
		foreach ($data as $key => $val) {
			
			if (substr(trim($key), 0, 6) == "order_") {
				$attr_id = (int) substr($key, 6);
				$this->db->query("UPDATE " . DB_PREFIX . "attribute 
								  SET sort_order={$val},is_default=" . (int) $data['is_default_' . $attr_id] . ",is_screen=" . (int) $data['is_screen_' . $attr_id] . "
								  WHERE attribute_id={$attr_id}");
				$this->db->query("UPDATE " . DB_PREFIX . "attribute_description
						SET name='{$data['attr_name_'.$attr_id]}' 
						WHERE attribute_id={$attr_id} AND language_id=" . (int) $this->config->get('config_language_id'));
			}
			if (substr($key, 0, 12) == "group_order_") {
				$attr_group_id = (int) substr($key, 12);
				$this->db->query("UPDATE " . DB_PREFIX . "attribute_group
						SET sort_order={$val}
						WHERE attribute_group_id={$attr_group_id}");
				$this->db->query("UPDATE " . DB_PREFIX . "attribute_group_description
						SET name='{$data['attr_group_name_'.$attr_group_id]}'
						WHERE attribute_group_id={$attr_group_id} AND language_id=" . (int) $this->config->get('config_language_id'));
			}
		}
		$this->cache->delete('category');
	}
	public function deleteCategory($category_id) {
		$this->db->query("DELETE FROM " . DB_PREFIX . "category WHERE category_id = '" . (int) $category_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "category_description WHERE category_id = '" . (int) $category_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "category_to_store WHERE category_id = '" . (int) $category_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "category_to_layout WHERE category_id = '" . (int) $category_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "product_to_category WHERE category_id = '" . (int) $category_id . "'");
		$this->db->query("DELETE FROM " . DB_PREFIX . "url_alias WHERE query = 'category_id=" . (int) $category_id . "'");
		
		$query = $this->db->query("SELECT category_id FROM " . DB_PREFIX . "category WHERE parent_id = '" . (int) $category_id . "'");
		
		foreach ($query->rows as $result) {
			$this->deleteCategory($result['category_id']);
		}
		
		$this->cache->delete('category');
	}
	public function getCategory($category_id) {
		$query = $this->db->query("SELECT DISTINCT *, (SELECT keyword FROM " . DB_PREFIX . "url_alias WHERE query = 'category_id=" . (int) $category_id . "') AS keyword FROM " . DB_PREFIX . "category WHERE category_id = '" . (int) $category_id . "'");
		
		return $query->row;
	}
	public function getCategories($parent_id = 0,$deep=1,$parent_name=1) {
		$category_data = $this->cache->get('category.' . (int) $this->config->get('config_language_id') . '.' . (int) $parent_id.'.'.(int) $deep.'.'.(int)$parent_name);
		if (!$category_data) {
			$category_data = array();
			
			$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "category c LEFT JOIN " . DB_PREFIX . "category_description cd ON (c.category_id = cd.category_id) WHERE c.parent_id = '" . (int) $parent_id . "' AND cd.language_id = '" . (int) $this->config->get('config_language_id') . "' ORDER BY c.sort_order, cd.name ASC");
			
			foreach ($query->rows as $result) {
				$category_data[] = array( 
					'category_id' => $result['category_id'], 
					'name' => $this->getPath($result['category_id'], $parent_name,$this->config->get('config_language_id')), 
					'status' => $result['status'], 
					'sort_order' => $result['sort_order'] 
				);
				if($deep==1){
					$category_data = array_merge($category_data, $this->getCategories($result['category_id']));
				}
			}
			
			$this->cache->set('category.' . (int) $this->config->get('config_language_id') . '.' . (int) $parent_id.'.'.(int) $deep.'.'.(int)$parent_name, $category_data);
		}
		
		return $category_data;
	}
	public function getPath($category_id,$parent_name=1) {
		$query = $this->db->query("SELECT name, parent_id FROM " . DB_PREFIX . "category c LEFT JOIN " . DB_PREFIX . "category_description cd ON (c.category_id = cd.category_id) WHERE c.category_id = '" . (int) $category_id . "' AND cd.language_id = '" . (int) $this->config->get('config_language_id') . "' ORDER BY c.sort_order, cd.name ASC");
		if($parent_name==1){
			if ($query->row['parent_id']) {
				return $this->getPath($query->row['parent_id'], $this->config->get('config_language_id')) . $this->language->get('text_separator') . $query->row['name'];
			}
			else {
				return $query->row['name'];
			}
		}else{
			return $query->row['name'];
		}
		
	}
	public function getCategoryDescriptions($category_id) {
		$category_description_data = array();
		
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "category_description WHERE category_id = '" . (int) $category_id . "'");
		
		foreach ($query->rows as $result) {
			$category_description_data[$result['language_id']] = array( 
				'name' => $result['name'], 
				'meta_keyword' => $result['meta_keyword'], 
				'meta_description' => $result['meta_description'], 
				'description' => $result['description'] 
			);
		}
		
		return $category_description_data;
	}
	public function getCategoryStores($category_id) {
		$category_store_data = array();
		
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "category_to_store WHERE category_id = '" . (int) $category_id . "'");
		
		foreach ($query->rows as $result) {
			$category_store_data[] = $result['store_id'];
		}
		
		return $category_store_data;
	}
	public function getCategoryLayouts($category_id) {
		$category_layout_data = array();
		
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "category_to_layout WHERE category_id = '" . (int) $category_id . "'");
		
		foreach ($query->rows as $result) {
			$category_layout_data[$result['store_id']] = $result['layout_id'];
		}
		
		return $category_layout_data;
	}
	public function getTotalCategories() {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "category");
		
		return $query->row['total'];
	}
	public function getTotalCategoriesByImageId($image_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "category WHERE image_id = '" . (int) $image_id . "'");
		
		return $query->row['total'];
	}
	public function getTotalCategoriesByLayoutId($layout_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "category_to_layout WHERE layout_id = '" . (int) $layout_id . "'");
		
		return $query->row['total'];
	}

	/**
	*
	**/
	public function updateCatName($data){
		$name=$data['title'];
		$id=$data['id'];
		if($name==""||!$name||!$id||$id==""){
			return 0;
		}else{
			if($this->db->query("UPDATE " . DB_PREFIX . "category_description SET name='".$name."' WHERE category_id = $id ")){
				$this->cache->delete('category');
				return 1;
			}else{
				return 0;
			}
		}
	}


	public function getAllCatsByParentIds($ids){
		$sql="SELECT GROUP_CONCAT(category_id) cat FROM " . DB_PREFIX . "category WHERE parent_id in (".$ids.")";
		$query = $this->db->query($sql);
		$cat_id=$query->row['cat'];
		if($cat_id){
			// echo $cat_ids;
			$cat_ids.=$cat_id.",".$this->getAllCatsByParentIds($cat_id);
			
		}else{
			return $cat_ids;
		}
		return $cat_ids;

	}

	/**
	*	导出比价网数据
	*	
	*/
	public function exportPrice($cat_ids){
		$cat_ids=substr(trim($cat_ids.",".$this->getAllCatsByParentIds($cat_ids)), 0, -1);
		$sql="SELECT p.product_id,p.image,p.upc,p.price,p.model,p.stock_status_id,pd.name,pd.description,pd.promot_phrase,cd.name category,m.name manu 
			  FROM " . DB_PREFIX . "product p 
			  LEFT JOIN " . DB_PREFIX . "product_description pd ON p.product_id=pd.product_id 
			  LEFT JOIN " . DB_PREFIX . "product_to_category pc ON p.product_id=pc.product_id 
			  LEFT JOIN " . DB_PREFIX . "category_description cd ON pc.category_id=cd.category_id 
			  LEFT JOIN " . DB_PREFIX . "manufacturer m ON p.manufacturer_id=m.manufacturer_id 
			  WHERE pd.language_id=".$this->config->get('config_language_id')." 
			  AND cd.language_id=".$this->config->get('config_language_id')." 
			  AND pc.category_id IN(".$cat_ids.")";
		$query=$this->db->query($sql);
		$products=$query->rows;
		return $products;
		//$sql="SELECT "
	}

}
?>